package com.ledong.se.string;

import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;

import org.apache.commons.lang.StringUtils;

public class TestParseTopicToLink {
    public static void main(String[] args) {
        // String weibo = "#UNIX#的基本哲学之一就是#创建#只做一件事并将这一件事#做好#";
        String weibo = "#iphone#的机器没有#android#机器开放性强##";
        if (StringUtils.countMatches(weibo, "#") < 2) {
            System.out.println("退出江湖");
            return;
        }

        int startLocat = weibo.indexOf("#");
        int endLocat = weibo.indexOf("#", startLocat + 1);

        while (startLocat > -1 && endLocat > -1) {
            System.out.print("startLocat : " + startLocat + "; endLocat : "
                    + endLocat + "\t");
            String topic_old = weibo.substring(startLocat, endLocat + 1);
            System.out.println(topic_old);
            String topic_new = parseTextToLink(topic_old);
            weibo = weibo.replace(topic_old, topic_new);
            startLocat = weibo.indexOf("#", weibo.lastIndexOf(topic_old)+ topic_old.length() + 1);
            endLocat = weibo.indexOf("#", startLocat + 1);
        }

        System.err.println(weibo);

    }

    public static String parseTextToLink(String text) {
        String encodingText = null;
        text = text.replace("#", "");
        try {
            encodingText = URLEncoder.encode(text, "UTF-8");
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        text = "<a href=\"http://s.weibo.com/weibo/" + encodingText + "\">#"
                + text + "#</a>";
        return text;
    }
}
